import React, { useState } from 'react';
import {
  Card,
  CardContent,
  CardActions,
  Typography,
  TextField,
  Button,
  Box,
  Avatar,
  IconButton,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  ImageList,
  ImageListItem,
  Chip,
  Alert,
  CircularProgress
} from '@mui/material';
import {
  Image as ImageIcon,
  Send as SendIcon,
  MoreVert as MoreVertIcon,
  ThumbUp as ThumbUpIcon,
  Comment as CommentIcon,
  Share as ShareIcon
} from '@mui/icons-material';
import { useAuth } from '../contexts/AuthContext';

function CommunityShare({ onPost }) {
  const [content, setContent] = useState('');
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const { user } = useAuth();

  const handleImageUpload = (event) => {
    const files = Array.from(event.target.files);
    const readers = files.map(file => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(file);
      });
    });

    Promise.all(readers).then(results => {
      setImages(prev => [...prev, ...results]);
    });
  };

  const handleSubmit = async () => {
    if (!content.trim() && images.length === 0) {
      setError('请输入分享内容或上传图片');
      return;
    }

    setLoading(true);
    try {
      await onPost({
        content,
        images,
        userId: user.id,
        username: user.username,
        timestamp: new Date()
      });
      setContent('');
      setImages([]);
      setError('');
    } catch (error) {
      setError('发布失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card sx={{ mb: 3 }}>
      <CardContent>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Avatar sx={{ bgcolor: 'primary.main' }}>
            {user?.username?.[0]?.toUpperCase()}
          </Avatar>
          <Box sx={{ flexGrow: 1 }}>
            <TextField
              fullWidth
              multiline
              rows={3}
              placeholder="分享你的环保心得..."
              value={content}
              onChange={(e) => setContent(e.target.value)}
              disabled={loading}
            />
            {images.length > 0 && (
              <ImageList sx={{ width: '100%', height: 120 }} cols={3} rowHeight={100}>
                {images.map((image, index) => (
                  <ImageListItem key={index}>
                    <img src={image} alt={`上传图片 ${index + 1}`} loading="lazy" />
                  </ImageListItem>
                ))}
              </ImageList>
            )}
            {error && (
              <Alert severity="error" sx={{ mt: 1 }}>
                {error}
              </Alert>
            )}
          </Box>
        </Box>
      </CardContent>
      <CardActions sx={{ justifyContent: 'space-between', px: 2 }}>
        <Box>
          <input
            accept="image/*"
            type="file"
            multiple
            id="image-upload"
            style={{ display: 'none' }}
            onChange={handleImageUpload}
          />
          <label htmlFor="image-upload">
            <IconButton component="span" color="primary">
              <ImageIcon />
            </IconButton>
          </label>
        </Box>
        <Button
          variant="contained"
          endIcon={loading ? <CircularProgress size={20} /> : <SendIcon />}
          onClick={handleSubmit}
          disabled={loading || (!content.trim() && images.length === 0)}
        >
          发布
        </Button>
      </CardActions>
    </Card>
  );
}

function CommunityPost({ post, onLike, onComment, onShare }) {
  const [anchorEl, setAnchorEl] = useState(null);
  const [commentOpen, setCommentOpen] = useState(false);
  const [comment, setComment] = useState('');

  const handleMenuClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const handleCommentSubmit = () => {
    if (comment.trim()) {
      onComment(post.id, comment);
      setComment('');
      setCommentOpen(false);
    }
  };

  return (
    <Card sx={{ mb: 2 }}>
      <CardContent>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <Avatar sx={{ mr: 2 }}>{post.username[0]}</Avatar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography variant="subtitle1">{post.username}</Typography>
            <Typography variant="caption" color="text.secondary">
              {new Date(post.timestamp).toLocaleString()}
            </Typography>
          </Box>
          <IconButton onClick={handleMenuClick}>
            <MoreVertIcon />
          </IconButton>
        </Box>

        <Typography variant="body1" paragraph>
          {post.content}
        </Typography>

        {post.images?.length > 0 && (
          <ImageList sx={{ width: '100%' }} cols={2} rowHeight={200}>
            {post.images.map((image, index) => (
              <ImageListItem key={index}>
                <img src={image} alt={`分享图片 ${index + 1}`} loading="lazy" />
              </ImageListItem>
            ))}
          </ImageList>
        )}

        {post.tags?.length > 0 && (
          <Box sx={{ mt: 1, display: 'flex', gap: 1, flexWrap: 'wrap' }}>
            {post.tags.map(tag => (
              <Chip key={tag} label={tag} size="small" />
            ))}
          </Box>
        )}
      </CardContent>

      <CardActions sx={{ justifyContent: 'space-between', px: 2 }}>
        <Button
          startIcon={<ThumbUpIcon />}
          onClick={() => onLike(post.id)}
          color={post.liked ? "primary" : "inherit"}
        >
          {post.likes || 0}
        </Button>
        <Button
          startIcon={<CommentIcon />}
          onClick={() => setCommentOpen(true)}
        >
          {post.comments?.length || 0}
        </Button>
        <Button
          startIcon={<ShareIcon />}
          onClick={() => onShare(post.id)}
        >
          分享
        </Button>
      </CardActions>

      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={handleMenuClose}>举报</MenuItem>
        <MenuItem onClick={handleMenuClose}>收藏</MenuItem>
      </Menu>

      <Dialog
        open={commentOpen}
        onClose={() => setCommentOpen(false)}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>发表评论</DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            multiline
            rows={3}
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            placeholder="写下你的评论..."
            sx={{ mt: 2 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCommentOpen(false)}>取消</Button>
          <Button
            variant="contained"
            onClick={handleCommentSubmit}
            disabled={!comment.trim()}
          >
            发表
          </Button>
        </DialogActions>
      </Dialog>
    </Card>
  );
}

export { CommunityShare, CommunityPost }; 